 
import pdfplumber
import xlwt
from watchdog.observers import Observer
import time
from watchdog.events import FileSystemEventHandler




class MyHandler(FileSystemEventHandler):  
    def on_modified(self, event):  
        print(f"modified: {event.src_path}") 
        if event.is_directory:  
            return None  
        elif event.src_path.endswith(".pdf"):   
            time.sleep(0.5)
            transfet_excel(pdf_path=event.src_path)
  
    def on_created(self, event):  
        print(f"created: {event.src_path}")  
        if event.is_directory:  
            return None  
        elif event.src_path.endswith(".pdf"):  
            time.sleep(0.5)
            transfet_excel(pdf_path=event.src_path)
  
    def on_deleted(self, event):  
        print(f"deleted: {event.src_path}")
        if event.is_directory:  
            return None  
  
        # elif event.src_path.endswith(".pdf"):  
            



def transfet_excel(pdf_path):
    # 定义保存Excel的位置
    workbook = xlwt.Workbook()  #定义workbook
    sheet = workbook.add_sheet('Sheet1')  #添加sheet
    i = 0 # Excel起始位置
    
    
    path = pdf_path
    #path = "aaaaaa.PDF"  # 导入PDF路径
    pdf = pdfplumber.open(path)
    # print('\n')
    print('开始读取excel')
    # print('\n')
    for page in pdf.pages:
        # 获取当前页面的全部文本信息，包括表格中的文字
        # print(page.extract_text())
        for table in page.extract_tables():
            # print(table)
            for row in table:
                # print(row)
                # if (row[0] == '本页小计'):
                #     continue
                for j in range(len(row)):
                    sheet.write(i, j, row[j])
                i += 1
            # print('---------- 分割线 ----------')
    pdf.close()
    # 保存Excel表
    workbook.save(path[:-4] + ".xls")



path = "D:\\downloads\\"  # 监控d盘下面的downloads
event_handler = MyHandler()  
observer = Observer()  
observer.schedule(event_handler, path, recursive=True)  
observer.start()  

try:  
    while True:  
        time.sleep(1)  
except KeyboardInterrupt:  
    observer.stop()  
observer.join()